/**
 * 业务表单基础的增、删、改、查
 */
import {
  init,
  list,
  del,
  exportData,
  importTemplate,
} from "@/views/youshuda/api/BaseApi";
import { getToken } from "@/utils/auth";
export const TableMixins = {
  components: {
    FormItem: () => import('@/views/youshuda/components/FormItem/index'),
    Edit: () => import('@/views/youshuda/components/FormEdit/index')
    // FlowableDealDialog: () => import('@/views/flowable/task/custom/FlowableDealDialog'),
    // //优树搭业务流程进度
    // MksFlowWorkProgress: () => import('@/views/components/common/MksFlowWorkProgress')
  },
  computed: {
    /**
      * 过滤表格中需要显示的字段
      */
    listShowColumnFilter() {
      let that = this;
      //过滤满足显示的字段信息
      return this.fieldInfo.filter((column, index, self) => {
        return column.isList == '1'
      });
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 当前编辑ID
      updateId: '',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 数据表格信息
      table: {
        //表格高度
        tabHeight: 0,
        _tabHeight: 0,
        // 总条数
        total: 0
      },
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示流程发起对话框
      procOpen: false,
      // 流程组件参数
      ProcParams: {},
      // 字段信息
      fieldInfo: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        timeParams: {}
      },
      //表格数据
      tableData: [],
      //判断当前模块是否启用流程
      isEnabledProc: '0',
      //数据导入配置
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
      },
      //优树搭业务流程进度配置信息
      mksFlowConfig: {
        title: "流程进度",
        taskUuid: "",
        isOpen: false
      }
    }
  },
  created() {
    /** 初始化字段信息 **/
    this.initField()
  },
  methods: {
    /** 初始化字段信息 **/
    initField() {
      if(!this.strIsNotEmpty(this.prefixUrl)){
        console.log("模块请求路径为空，中止加载...");
        return;
      }
      init(this.prefixUrl).then(res => {
        if (res.code == 200) {
          let fieldInfo = res.data
          this.fieldInfo = fieldInfo
          fieldInfo.forEach(item => {
            //查询参数
            this.queryParams[item.columnName] = null
          })
          //判断当前模块是否启用流程
          if (fieldInfo != null) {
            this.isEnabledProc = fieldInfo[0]['isEnabledProc']
          }
        } else {
          this.msgError(res.msg)
        }
      }).then(res => {
        /** 获取列表数据 **/
        this.getList()
      })
    },
    /** 查询附件列表 */
    getList() {
      this.loading = true
      //清空当前数据
      this.tableData = []
      //请求数据
      list(this.prefixUrl, this.queryParams).then(response => {
        this.tableData = response.rows
        this.table.total = response.total
        this.loading = false
        // 重置数据表格的高度
        this.resetTableHeight()
      })
    },
    /** 表单同步数据 **/
    ItemValChange(data) {
      console.log(data);
      if(data.type=='timeParams'){
        if(data.val==null){
          this.queryParams['timeParams'][data.key]=null
        }else{
          this.queryParams['timeParams'][data.key] = JSON.stringify(data.val)
        }
      }else{
        this.queryParams[data.key] = data.val
      }
    },
    /** 取消按钮 **/
    cancel(param) {
      this.updateId = ''
      this.open = false
      this.procOpen = false;
      if (param != undefined && param.isRef == true) {
        this.getList()
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置查询表单信息 **/
    resetQuery() {
      this.queryParams['timeParams']={}
      this.fieldInfo.forEach((item, index) => {
        this.$set(this.fieldInfo[index], 'fieldData', null)
        this.queryParams[item.columnName] = null
      })
      this.handleQuery()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.updateId = ''
      this.open = true
      this.title = '添加' + this.componentDesc
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids
      this.updateId = id
      this.open = true
      this.title = '修改' + this.componentDesc
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this;
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除勾选数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return del(that.prefixUrl, ids);
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this;
      const queryParams = JSON.parse(JSON.stringify(this.queryParams));
      queryParams['pageSize'] = 20000;
      this.$confirm('是否确认导出当前查询结果所有数据，最多可导出20000条数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        that.download(that.prefixUrl+'/export', {
          ...that.queryParams
        }, `${that.componentDesc+'_'+new Date().getTime()}.xlsx`)
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = this.componentDesc;
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(this.prefixUrl+'/importTemplate', {
        ...this.queryParams
      }, `${this.componentDesc+'_模块'}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    // 重置数据表格的高度
    resetTableHeight() {
      this.$nextTick(() => {
        this.table.tabHeight = this.table._tabHeight
        if(this.showSearch){
          /**
           * 显示搜索区域时
           */
          this.table.tabHeight = this.table._tabHeight-this.$refs.queryForm.$el.offsetHeight
        }
        // 重新渲染表格
        this.$refs.tables.doLayout();
      })
    },

  },
  beforeMount() {
    /** 适配数据表格高度 **/
    this.table._tabHeight = this.appMain.height - 130
  },
  // 页面缓存重新进入页面时，在路由组件被激活时触发
  activated() {
    this.$nextTick(() => {
      this.$refs.tables.doLayout(); // 对表格重新布局（解决切换页面后列错乱）
    })
  },

  watch: {
    /** 监听查询输入是否显示，适配数据表格高度 **/
    showSearch: {
      immediate: true,
      handler(nowdata) {
        this.resetTableHeight();
      }
    }

  }
}
